﻿// src/stores/axiosStore.js
import { defineStore } from 'pinia';
import axios from 'axios';
import { ref } from 'vue';

export const useAxiosStore = defineStore('axiosStore', () => {
    const users = ref([]);
    const loading = ref(false);
    const error = ref(null);
    const result = ref(null);

    // 带有拦截器的 Axios 实例
    const axiosInstance = axios.create();

    axiosInstance.interceptors.request.use(
        (config) => {
            console.log('请求拦截器:', config);

            // 添加时间戳并存储到 localStorage 中
            const timestamp = new Date().toISOString();
            const stateWithTimestamp = {
                state: 'zzu',
                timestamp: timestamp
            };
            localStorage.setItem('stateWithTimestamp', JSON.stringify(stateWithTimestamp));

            return config;
        },
        (err) => {
            return Promise.reject(err);
        }
    );

    axiosInstance.interceptors.response.use(
        (response) => {
            console.log('响应拦截器:', response);

            // 处理并格式化数据
            if (response.data && response.data.data) {
                const formattedData = response.data.data.map(user => ({
                    id: user.id,
                    name: `${user.first_name} ${user.last_name}`,
                    email: user.email,
                    avatar: user.avatar
                }));
                response.data.formattedData = formattedData;
            }

            return response;
        },
        (err) => {
            return Promise.reject(err);
        }
    );

    const fetchUsers = async () => {
        loading.value = true;
        error.value = null;
        try {
            const response = await axiosInstance.get('https://reqres.in/api/users');
            if (response.data.formattedData) {
                users.value = response.data.formattedData;  // 使用格式化后的数据
            }
            console.log('users:', users.value);
        } catch (err) {
            error.value = err.message;
        } finally {
            loading.value = false;
        }
    };

    const createUser = async (userData) => {
        loading.value = true;
        error.value = null;
        try {
            const response = await axiosInstance.post('https://reqres.in/api/users', userData);
            if (response.data) {
                const formattedUser = {
                    id: response.data.id,
                    name: `${response.data.first_name} ${response.data.last_name}`,
                    email: response.data.email,
                    avatar: response.data.avatar,
                    createdAt: response.data.createdAt,
                };
                users.value.push(formattedUser);
                result.value = formattedUser;
                console.log('response:', formattedUser);
            }
        } catch (err) {
            error.value = err.message;
        } finally {
            loading.value = false;
        }
    };

    return {
        users,
        loading,
        error,
        fetchUsers,
        createUser,
        result,
    };
});
